<script lang="ts" setup>
import { getPatientConsultOrderDetailAPI } from '@/apis/consult'
import { useUserStore } from '@/stores/user'
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult'
import { io, type Socket } from '@hyoga/uni-socket.io'
import { ref } from 'vue'
import RoomStatus from './components/room-status.vue'
import { type ChatMsgListData, type MsgItem } from '@/types/room'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import { postUploadAPI } from '@/apis/common'
import PrescriptionInfo from './components/prescription-info.vue'

const props = defineProps<{
  orderId: string
  type: string
  payResult: 'true' | 'false'
}>()
const store = useUserStore()
const socket = io('https://consult-api.itheima.net', {
  auth: { token: `Bearer ${store.token}` },
  query: { orderId: props.orderId },
  transports: ['websocket', 'polling'],
  timeout: 5000,
})
//获取订单详情
const orderDetail = ref<GetPatientConsultOrderDetailData>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  // console.log(res);
  orderDetail.value = res.data
}
getOrderDetail()
//监听订单状态
socket.on('statusChange', () => {
  // console.log('statuschange', data)
  getOrderDetail()
})
//消息列表
const messageList = ref<MsgItem[]>([])
//历史事件
socket.on('chatMsgList', (res: ChatMsgListData) => {
  if (res.code !== 10000) {
    return
  }
  res.data?.forEach((item) => {
    if (item.items) {
      messageList.value.push(...item.items)
    }
  })
})
//接收回复消息
socket.on('receiveChatMsg', (res: MsgItem) => {
  messageList.value.push(res)
  socket.emit('updateMsgStatus', res.id)
})

// 连接成功
socket.on('connect', () => {
  console.log('连接成功')
  // console.log(orderDetail.value)
})
socket.on('disconnect', () => {
  console.log('连接失败')
})
//发送消息
const textMessage = ref('')
const sendMessage = () => {
  if (textMessage.value.trim() == '') {
    uni.showToast({
      title: '请输入内容',
      icon: 'none',
    })
    return
  }
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: 1,
    msg: {
      content: textMessage.value,
    },
  })
  textMessage.value = ''
}
//图片上传
const handleUploadImage = async () => {
  if (orderDetail.value?.status !== OrderStatus.ZiXunZhong) {
    uni.showToast({
      title: '咨询已结束',
      icon: 'none',
    })
    return
  }
  const { tempFilePaths } = await uni.chooseImage({
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  })
  // 上传图片，传递图片路径
  const res = await postUploadAPI(tempFilePaths[0])
  console.log(res)
}
</script>

<template>
  <view class="room-page">
    <!-- 咨询室状态 -->
    <RoomStatus
      v-if="orderDetail"
      :status="orderDetail?.status"
      :statusValue="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <!-- 消息列表 -->
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <view v-for="item in messageList" :key="item.id">
          <!-- 患者信息 -->
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <!-- 气泡消息 -->
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <!-- 电子处方 -->
          <PrescriptionInfo
            v-else-if="item.msgType === 22 && item.msg?.prescription"
            :info="item.msg.prescription"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="textMessage"
          @confirm="sendMessage"
          :disabled="orderDetail?.status !== OrderStatus.ZiXunZhong"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="handleUploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './room.scss';
</style>
